package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.yaml.snakeyaml.events.Event;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @author 苏靓仔
 * @version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

	private final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

	@Autowired
	private JwtProperties jwtProperties;
	@Autowired
	private WeChatProperties weChatProperties;

	@Autowired
	private UserMapper userMapper;

	@Override
	public UserLoginVO login(UserLoginDTO userLoginDTO) {
		// 调用微信接口服务，获取当前微信用户的openid
		String openid = wx_getOpenId(userLoginDTO.getCode());
		// 判断openid是否为空
		if (!StringUtils.hasText(openid)){
			throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
		}
		// 判断当前用户是否为新用户
		User user = userMapper.getUserByOpenid(openid);
		if (ObjectUtils.isEmpty(user)){
			// 如果是新用户，自动完成注册
			user = User.builder()
					.openid(openid)
					.createTime(LocalDateTime.now())
					.build();
			userMapper.insert(user);
		}
		// 为微信用户生成jwt令牌
		HashMap<String, Object> claims = new HashMap<>();
		claims.put(JwtClaimsConstant.USER_ID,user.getId());
		String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
		UserLoginVO userLoginVO = UserLoginVO.builder()
				.token(token)
				.openid(openid)
				.id(user.getId())
				.build();
		return userLoginVO;
	}

	/**
	 * // 调用微信接口服务，获取当前微信用户的openid
	 * @param code
	 * @return
	 */
	private String wx_getOpenId(String code){
		// 调用微信接口服务，获取当前微信用户的openid
		HashMap<String, String> map = new HashMap<>();
		map.put("appid",weChatProperties.getAppid());
		map.put("secret",weChatProperties.getSecret());
		map.put("js_code",code);
		map.put("grant_type","authorization_code");
		String json = HttpClientUtil.doGet(WX_LOGIN, map);
		JSONObject jsonObject = JSON.parseObject(json);
		String openid = jsonObject.getString("openid");
		return openid;
	}
}
